from flask import Flask, request, redirect, url_for, render_template
import os

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['ALLOWED_EXTENSIONS'] = {'docx'}

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']

@app.route('/')
def index():
    return render_template('upload.html')


@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return '没有选择文件'

    file = request.files['file']
    question_type = request.form['question_type']

    if file and allowed_file(file.filename):
        filename = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
        file.save(filename)
        print(f"文件已保存为: {filename}")  # 添加日志

        questions = extract_questions(filename, question_type)
        print(f"提取到的题目: {questions}")  # 添加日志
        insert_questions('Sample Exam', questions, question_type)

        return redirect(url_for('upload_success'))
    return '文件格式不正确'


@app.route('/upload_success')
def upload_success():
    return '文件上传和数据插入成功！'

if __name__ == '__main__':
    if not os.path.exists(app.config['UPLOAD_FOLDER']):
        os.makedirs(app.config['UPLOAD_FOLDER'])
    app.run(host='0.0.0.0', port=5000, debug=True)
